package com.my.test.java.http;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;

import javax.activation.MimetypesFileTypeMap;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import java.nio.charset.Charset;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;


public class HttpUtils {
	
	private static final int ConnectTimeout = 30000;
	private static final int ReadTimeout = 30000;

	public  String sendGet(String url, String param,String cookies) {
        String result = "";
        BufferedReader in = null;
        try {
        	String urlNameString = url;
        	param=(param==null?"":param);
        	if (url.indexOf("?")>0) {
        		urlNameString = url+param;
			}else if (!param.isEmpty()) {
				urlNameString = url + "?"+param;
			}
            URL realUrl = new URL(urlNameString);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            if(connection instanceof HttpsURLConnection)
            {
                SSLContext sc = SSLContext.getInstance("SSL");
                sc.init(null, new TrustManager[]{new TrustAnyTrustManager()}, new java.security.SecureRandom());
                ((HttpsURLConnection) connection).setSSLSocketFactory(sc.getSocketFactory());
                ((HttpsURLConnection) connection).setHostnameVerifier(new TrustAnyHostnameVerifier());
            }
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            if (cookies!=null&&!cookies.isEmpty()) {
            	connection.setRequestProperty("Cookie", cookies);
			}
            connection.setConnectTimeout(ConnectTimeout);
            connection.setReadTimeout(ReadTimeout);
            
            // 建立实际的连接
            connection.connect();
            // 获取所有响应头字段
            //Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
//            for (String key : map.keySet()) {
//                System.out.println(key + "--->" + map.get(key));
//            }
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
            result=new String(result.getBytes(),"utf-8");
        } catch (Exception e) {
//            System.out.println("发送GET请求出现异常！" + e);
//            e.printStackTrace();
            throw new RuntimeException(url+"发送 GET 请求出现异常！",e);
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }
	
	public void doPost(String url){
		URL myUrl = null;
		try {
			myUrl = new URL(url);
			URLConnection urlConn = myUrl.openConnection();
			String myCookie = "4AOEWXM5QTBSTE2JQWW6VFWQ5ONB2XIYBIRIFH6IG3CJE7AO42JSOADXODLXW3HNVHY4QI333IIP5RJFDIIVBEQ3RRQSSECVMKAQQ67X2AXBBSUIRVU6SYWCDRVCILKVVVWQAUGFK43HZ6N3AF3SAO4QXMBVTFHOREII3MISVJP5KSPKGI6Q2LCVIJE57CUA5ODS2F3OKHOLOZMPHGB5FLHRPGAHOQQMXCG45EI44XNXNXKIULGAJOJSXYTDST4G7AEYPG32DT77UVVBQ65NQWB6MKHLRICJV5TKWFRW6A6BWKJE7RP2YKKOAH3IBEZVFOSFQPXW2WFDCQFWSSGVWGWJ364DUZHKD2X27QG2Y6PZJNXUCCGUWLI5GV3O43U6Y2M5FOIXB6P6MNMPJ562K5T3EVURJMBTFINQN7Q"; 
			
			urlConn.setRequestProperty("hi_dxh", myCookie);
			urlConn.connect();
			HttpURLConnection connection = null;
            if(urlConn instanceof HttpURLConnection){
            	connection = (HttpURLConnection) urlConn;
            }else{
            	System.out.println("Please enter an HTTP URL.");
            	return;
           }
           BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream(),"utf-8"));
	       String urlString = "";
	       String current;
	       while((current = in.readLine()) != null){
	          urlString += current;
	       }
	       System.out.println(urlString);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	
	 private static class TrustAnyTrustManager implements X509TrustManager{

	        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException{
	        }

	        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException{
	        }

	        public X509Certificate[] getAcceptedIssuers(){
	            return new X509Certificate[]{};
	        }
	    }

	    private static class TrustAnyHostnameVerifier implements HostnameVerifier{
	        public boolean verify(String hostname, SSLSession session){
	            return true;
	        }
	    }
}
